/**
 * 链接信息视图组件
 */
class LinksView {
    constructor(route) {
        this.route = route;
        this.title = route.title || '链接信息';
        this.table = null;
        this.refreshTimer = null;
    }
    
    /**
     * 渲染页面内容
     */
    async render() {
        return `
            <div class="layui-fluid content-wrapper">
                <div class="content-header">
                    <h2>链接信息</h2>
                </div>
                
                <div class="layui-card">
                    <div class="layui-card-header">
                        <div class="layui-form" lay-filter="search-form">
                            <div class="layui-form-item" style="margin-bottom: 0;">
                                <div class="layui-inline">
                                    <label class="layui-form-label">状态筛选</label>
                                    <div class="layui-input-inline">
                                        <select name="status" lay-filter="status-filter">
                                            <option value="">全部</option>
                                            <option value="active">活跃</option>
                                            <option value="inactive">非活跃</option>
                                            <option value="error">错误</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">搜索</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="keyword" placeholder="输入关键词" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn layui-btn-sm" lay-submit lay-filter="search-btn">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-filter="reset-btn">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-card-body">
                        <table class="layui-table" id="links-table" lay-filter="links-table">
                            <thead>
                                <tr>
                                    <th lay-data="{field:'id', width:60, sort:true}">ID</th>
                                    <th lay-data="{field:'name', width:150}">名称</th>
                                    <th lay-data="{field:'url', width:200}">URL</th>
                                    <th lay-data="{field:'status', width:80, templet:'#statusTpl'}">状态</th>
                                    <th lay-data="{field:'latency', width:100, sort:true}">延迟(ms)</th>
                                    <th lay-data="{field:'requests', width:100, sort:true}">请求数</th>
                                    <th lay-data="{field:'errors', width:80, sort:true}">错误数</th>
                                    <th lay-data="{field:'lastCheck', width:150}">最后检查</th>
                                    <th lay-data="{fixed:'right', width:150, toolbar:'#tableToolbar'}">操作</th>
                                </tr>
                            </thead>
                        </table>
                        
                        <!-- 状态模板 -->
                        <script type="text/html" id="statusTpl">
                            {{# if(d.status === 'active'){ }}
                                <span class="layui-badge layui-bg-green">活跃</span>
                            {{# } else if(d.status === 'inactive'){ }}
                                <span class="layui-badge">非活跃</span>
                            {{# } else if(d.status === 'error'){ }}
                                <span class="layui-badge layui-bg-red">错误</span>
                            {{# } else { }}
                                <span class="layui-badge layui-bg-gray">未知</span>
                            {{# } }}
                        </script>
                        
                        <!-- 操作按钮模板 -->
                        <script type="text/html" id="tableToolbar">
                            <a class="layui-btn layui-btn-xs" lay-event="check">检查</a>
                            <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</a>
                            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
                        </script>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 初始化组件
     */
    async init() {
        console.log('链接信息组件初始化');
        
        // 等待DOM加载
        await this.waitForDOM();
        
        // 初始化表格
        this.initTable();
        
        // 绑定事件
        this.bindEvents();
        
        // 启动定时刷新
        this.startAutoRefresh();
        
        // 使用LayUI渲染
        if (typeof layui !== 'undefined') {
            layui.use(['element', 'layer', 'table', 'form'], function() {
                var element = layui.element;
                var layer = layui.layer;
                var table = layui.table;
                var form = layui.form;
                
                element.render();
                form.render();
                
                // 渲染表格
                this.table = table.render({
                    elem: '#links-table',
                    data: this.generateMockData(),
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    toolbar: true,
                    defaultToolbar: ['filter', 'exports', 'print'],
                    done: function(res, curr, count) {
                        console.log('表格渲染完成', res, curr, count);
                    }
                });
            }.bind(this));
        }
    }
    
    /**
     * 等待DOM加载
     */
    waitForDOM() {
        return new Promise((resolve) => {
            if (document.getElementById('links-table')) {
                resolve();
            } else {
                setTimeout(() => resolve(), 100);
            }
        });
    }
    
    /**
     * 初始化表格
     */
    initTable() {
        // 生成模拟数据
        const data = this.generateMockData();
        
        // 使用LayUI表格渲染
        if (typeof layui !== 'undefined') {
            layui.use(['table'], function() {
                var table = layui.table;
                
                this.table = table.render({
                    elem: '#links-table',
                    data: data,
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    toolbar: true,
                    defaultToolbar: ['filter', 'exports', 'print'],
                    done: function(res, curr, count) {
                        console.log('表格渲染完成', res, curr, count);
                    }
                });
            }.bind(this));
        }
    }
    
    /**
     * 生成模拟数据 - 已移除
     * 需要连接真实数据接口
     */
    generateMockData() {
        return []; // 静态假数据已移除
    }
    
    /**
     * 格式化日期时间
     */
    formatDateTime(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const self = this;
        
        // 监听表格工具条事件
        layui.use(['table', 'layer'], function() {
            var table = layui.table;
            var layer = layui.layer;
            
            // 监听工具条
            table.on('tool(links-table)', function(obj) {
                var data = obj.data;
                
                if (obj.event === 'check') {
                    self.checkLink(data);
                } else if (obj.event === 'edit') {
                    self.editLink(data);
                } else if (obj.event === 'delete') {
                    self.deleteLink(data, obj);
                }
            });
            
            // 监听搜索表单
            form.on('submit(search-btn)', function(data) {
                self.searchLinks(data.field);
                return false;
            });
            
            // 监听重置按钮
            form.on('submit(reset-btn)', function() {
                self.resetSearch();
                return false;
            });
            
            // 监听状态筛选
            form.on('select(status-filter)', function(data) {
                self.filterByStatus(data.value);
            });
        });
    }
    
    /**
     * 检查链接 - 移除模拟数据
     */
    checkLink(data) {
        layer.msg('检查链接功能需要连接真实数据接口', {icon: 5});
    }
    
    /**
     * 编辑链接
     */
    editLink(data) {
        layer.open({
            type: 1,
            title: '编辑链接',
            area: ['500px', '400px'],
            content: `
                <div style="padding: 20px;">
                    <form class="layui-form" lay-filter="edit-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="name" value="${data.name}" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">URL</label>
                            <div class="layui-input-block">
                                <input type="text" name="url" value="${data.url}" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-block">
                                <select name="status">
                                    <option value="active" ${data.status === 'active' ? 'selected' : ''}>活跃</option>
                                    <option value="inactive" ${data.status === 'inactive' ? 'selected' : ''}>非活跃</option>
                                    <option value="error" ${data.status === 'error' ? 'selected' : ''}>错误</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="save-btn">保存</button>
                                <button class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            `,
            success: function(layero, index) {
                layui.form.render();
                
                layui.form.on('submit(save-btn)', function(formData) {
                    layer.msg('保存成功！', {icon: 1});
                    layer.close(index);
                    this.refreshTable();
                    return false;
                }.bind(this));
            }.bind(this)
        });
    }
    
    /**
     * 删除链接
     */
    deleteLink(data, obj) {
        layer.confirm(`确定要删除链接 "${data.name}" 吗？`, {
            btn: ['确定', '取消']
        }, function() {
            layer.msg('删除成功！', {icon: 1});
            obj.del(); // 删除表格行
        });
    }
    
    /**
     * 搜索链接
     */
    searchLinks(params) {
        console.log('搜索参数:', params);
        
        // 静态假数据已移除 - 需要连接真实数据接口
        if (this.table) {
            layer.msg('搜索功能需要连接真实数据接口', {icon: 5});
            return;
            
            // this.table.reload({data: filteredData}); // 假数据已移除
        }
    }
    
    /**
     * 重置搜索
     */
    resetSearch() {
        // 重置表单
        layui.form.val('search-form', {
            keyword: '',
            status: ''
        });
        
        // 重新加载数据
        this.refreshTable();
    }
    
    /**
     * 按状态筛选
     */
    filterByStatus(status) {
        if (this.table) {
            const tableData = this.generateMockData();
            const filteredData = status ? tableData.filter(item => item.status === status) : tableData;
            this.table.reload({data: filteredData});
        }
    }
    
    /**
     * 刷新表格
     */
    refreshTable() {
        if (this.table) {
            this.table.reload({data: this.generateMockData()});
        }
    }
    
    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        // 每30秒自动刷新一次
        this.refreshTimer = setInterval(() => {
            this.refreshTable();
        }, 30000);
    }
    
    /**
     * 停止自动刷新
     */
    stopAutoRefresh() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
        }
    }
    
    /**
     * 清理资源
     */
    destroy() {
        console.log('链接信息组件销毁');
        
        // 停止自动刷新
        this.stopAutoRefresh();
        
        // 清理事件监听
        layui.form.off('submit(search-btn)');
        layui.form.off('submit(reset-btn)');
        layui.form.off('select(status-filter)');
        
        // 销毁表格
        if (this.table) {
            this.table = null;
        }
    }
}

// 注册到全局视图组件
if (!window.ViewComponents) {
    window.ViewComponents = {};
}
window.ViewComponents.links = LinksView;